package thread;

import utils.PrintlnUtils;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/*
    FutureTask介绍及使用
    https://blog.csdn.net/qq1137623160/article/details/79772505

    FutureTask详解
    https://blog.csdn.net/qq_39654841/article/details/90631795
 */
public class TestFutureTask {
    public static void main(String[] args) {
        Callable<Integer> call = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                PrintlnUtils.println("在计算结果...");
                Thread.sleep(3000);
                return 1;
            }
        };

        FutureTask<Integer> task = new FutureTask<>(call);
        Thread thread = new Thread(task);
        thread.start();
        PrintlnUtils.println("处理其他事情...");
        Integer result = null;

        task.cancel(true);
        PrintlnUtils.println("isCancelled  = "+task.isCancelled());

        try {
            result = task.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
            PrintlnUtils.println("InterruptedException 异常 " + e.toString());
        } catch (ExecutionException e) {
            e.printStackTrace();
            PrintlnUtils.println("ExecutionException 异常 " + e.toString());
        } catch (Exception e) {
            PrintlnUtils.println("Exception 异常 " + e.toString());
            //Exception 异常 java.util.concurrent.CancellationException
        }
        PrintlnUtils.println("计算结果：" + result);
    }
}
